package web.jdbc.function;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.StringJoiner;

import web.clazz.Clazz;
import web.jdbc.DataOperator;
/**用于更新Entity
 * @author 乐渊
 * @version 1.0
 * @see DataOperator
 * */
public class Update<T> {
	
	private static PreparedStatement ps = null;
	private Connection conn = null;
	private T t;
	private Clazz clazz = null;
	
	public Update(Connection conn,T t,Clazz clazz) {
		this.conn = conn;
		this.t = t;
		this.clazz = clazz;
	}
	
	public void getRS() throws SQLException{
		
		StringJoiner sql = new StringJoiner("");
		sql.add("UPDATE " + clazz.getName() + " SET ");
	    
	    new DataOperator<T>().collectData(this.t, this.clazz);
	    
	    for (int i = 0; i < DataOperator.columns.size(); i++) {
	      sql.add(DataOperator.columns.get(i) + "=?,");
	    }
	    
	    sql.add(" WHERE " + DataOperator.keyColumn + "=?");
	    String sql2 = sql.toString();
	    sql2 = sql2.replace(", WHERE", " WHERE");
	    ps = this.conn.prepareStatement(sql2);
	    for (int i = 0; i < DataOperator.columns.size(); i++) {
	      DataOperator.setData(ps, i + 1, DataOperator.values.get(i));
	    }
	    DataOperator.setData(ps, DataOperator.columns.size() + 1, DataOperator.keyValue);
	    ps.execute();
	    ps.close();
	}
}
